#!/bin/bash

usage() {
	cat <<EOF
usage: basign-key -u <key_to_sign_with> -s <key_to_sign>

  -s <key>    Specify the key to sign.
  -u <key>    Specify the key to sign with. If <key> is a master key name,
              it is resolved.

  Valid master key names:
    - paraxor
    - noptrix
    - nrz
EOF
}

parse_args() {
	while [[ "$1" ]] ; do
		case "$1" in
			-u)
				key_to_use=$2
				shift
				;;
			-s)
				key_to_sign=$2
				shift
				;;
			-h)
				usage
				exit
				;;
			*)
				usage
				exit 1
				;;
		esac
		shift
	done
}

resolve_key_name() {
	case "$key_to_use" in
		paraxor)
			key_to_use=8F9A9793CB8591147C2EC70566E0CDBD1E01F333
			;;
		noptrix)
			key_to_use=CBA3C7D4798912702DCF568E67D8BDF42AD93F4E
			;;
		nrz)
			key_to_use=A0917C4147A37007CB54C1CFD295AA940EFDDF62
			;;
	esac
	echo "signing $key_to_sign with $key_to_use."
}

check_keys() {
	if [[ -z "$key_to_use" || -z "$key_to_sign" ]] ; then
		usage
		exit 1
	fi
}

get_key() {
	gpg --keyserver hkp://pgp.mit.edu --recv-key "$key_to_sign"
}

sign_key() {
	gpg --default-key "$key_to_use" --sign-key "$key_to_sign"
}

send_key() {
	gpg --keyserver hkp://pgp.mit.edu --send-keys "$key_to_sign"
}

main() {
	parse_args "$@"

	resolve_key_name
	check_keys

	get_key
	sign_key
	send_key
}

main "$@"
